<?php

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);    
    }
    
    return $str;
}


function _convert($content) { 
    if(!mb_check_encoding($content, 'UTF-8') 
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) { 

        $content = mb_convert_encoding($content, 'UTF-8'); 

        if (mb_check_encoding($content, 'UTF-8')) { 
            // log('Converted to UTF-8'); 
        } else { 
            // log('Could not converted to UTF-8'); 
        } 
    } 
    return $content; 
} 

function firstOfPrevMonth() {
return date("Y.m.d", strtotime(date('n', mktime(0,0,0,(date('m')-1),28,date('Y'))).'/01/'.date('Y',mktime(0,0,0,(date('m')-1),28,date('Y'))).' 00:00:00'));
}

function lastOfPrevMonth() {
return date("Y.m.d", strtotime('-1 second',strtotime('+1 month',strtotime(date('n', mktime(0,0,0,(date('m')-1),28,date('Y'))).'/01/'.date('Y',mktime(0,0,0,(date('m')-1),28,date('Y'))).' 00:00:00'))));
}


function firstOfMonth() {
return date("Y.m.d", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}

function lastOfMonth() {
return date("Y.m.d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}

function adddays($data,$dienos) {
list($year,$month,$day  ) = explode('.', $data);
return date("Y.m.d", strtotime('+' . $dienos .' day',  strtotime($month."/".$day."/".$year)));
}

/* 
## converts a given date format to another date format returns date if the checked date given is valid; otherwise returns NULL
## $s_date the date in e.g. dd/mm/yyyy
## $s_from, $s_to date formats from to i.e. convertdate('13/04/2009','eng','iso','-'); output: 2009-04-13
## date formats available
## 'eng' = dd/mm/yyyy
## 'usa' = mm/dd/yyyy
## 'iso' = yyyy/mm/dd
## $s_return_delimiter returned delimiter e.g. '-' would return dd-mm-yyyy 
*/
function convertdate($s_date,$s_from,$s_to,$s_return_delimiter) {

    $s_return_date = '';
    $s_from = strtolower($s_from);
    $s_to = strtolower($s_to);
    $s_date = str_replace(array('\'', '-', '.', ',', ' '), '/', $s_date);
    $a_date = explode('/', $s_date); 
    
	if (count($a_date)==3) {
    switch($s_from) {
        case 'eng': # dd/mm/yyyy
            $day = $a_date[0];
            $month = $a_date[1];
            $year = $a_date[2]; 
        break;
        case 'usa':  # mm/dd/yyyy
            $month = $a_date[0];
            $day = $a_date[1];
            $year = $a_date[2]; 
        break;
        case 'iso': # yyyy/mm/dd
            $year = $a_date[0]; 
            $month = $a_date[1];
            $day = $a_date[2];
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_from not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }
	} else {
		return NULL;
	}
    # substitution fixes of valid alternative human input e.g. 1/12/08
    if (strlen($day)==1) { $day='0'.$day; } # day -trailing zero missing
    if (strlen($month)==1) { $month='0'.$month; } # month -trailing zero missing
    if (strlen($year)==3) { $year=substr(date('Y'),0,strlen(date('Y'))-3).$year; } # year -millennium missing
    if (strlen($year)==2) { $year=substr(date('Y'),0,strlen(date('Y'))-2).$year; } # year -century missing
    if (strlen($year)==1) { $year=substr(date('Y'),0,strlen(date('Y'))-1).$year; } # year -decade missing

    switch($s_to) {
        case 'eng': # dd/mm/yyyy
            $s_return_date = $day.$s_return_delimiter.$month.$s_return_delimiter.$year;
        break;
        case 'usa':  # mm/dd/yyyy
            $s_return_date = $month.$s_return_delimiter.$day.$s_return_delimiter.$year;
        break;
        case "iso": # yyyy/mm/dd
            $s_return_date = $year.$s_return_delimiter.$month.$s_return_delimiter.$day;
        break;
        default: # error message
            user_error('function convertdate(string $s_date, string $s_from, string $s_to, string $s_return_delimiter) $s_to not a valid type of \'eng\', \'usa\' or \'iso\'');
            return NULL;
    }

    # if it's an invalid calendar date e.g. 40/02/2009 or rt/we/garbage
    if (!is_numeric($month) || !is_numeric($day) || !is_numeric($year)) { 
        return NULL;
    } elseif (!checkdate($month, $day, $year)) {
        return NULL;
    }

    return $s_return_date;
} 

function toLit($NumberArg,$curr) {

if ($NumberArg < 1) {
	if ($curr == "LTL")
		$strRez = "NULIS LITŲ ";
	else
		$strRez = "NULIS EURŲ ";
	return $strRez;
}

$strMillions = floor($NumberArg/1000000);
$m2 = "";
$m1 = "";
If ($strMillions > 0) {
	$m1 = TrysSkaitmenys($strMillions);
	$v = $strMillions % 100;
	$d = $strMillions % 10;
	if ($v >=10 && $v <20) {
		$m2 = "MILIJONŲ ";
	} else {
		switch ($d) {
			case 0:
				$m2 = "MILIJONŲ ";
				break;
			case 1:
				$m2 = "MILIJONAS ";
				break;
			default:
				$m2 = "MILIJONAI ";
		}
	}
}


$strThousands = floor(($NumberArg % 1000000)/1000);
$t2 = "";
$t1 = "";
If ($strThousands > 0) {
	$t1 = TrysSkaitmenys($strThousands);
	$v = $strThousands % 100;
	$d = $strThousands % 10;
	if ($v >=10 && $v <20) {
		$t2 = "TŪKSTANČIŲ ";
	} else {
		switch ($d) {
			case 0:
				$t2 = "TŪKSTANČIŲ ";
				break;
			case 1:
				$t2 = "TŪKSTANTIS ";
				break;
			default:
				$t2 = "TŪKSTANČIAI ";
		}
	}
}

$strHundreds = $NumberArg % 1000;

//echo $strHundreds;

$r1 = TrysSkaitmenys($strHundreds);
	$v = $strHundreds % 100;
	$d = $strHundreds % 10;
	if ($curr == "LTL")
		$r2 = "Lt ";
	else
		$r2 = "Eur ";

$ct = round(fmod(($NumberArg *100) , 100));

return $m1 . $m2 . $t1 . $t2 . $r1 . $r2 . " " . $ct ." ct";

}


function TrysSkaitmenys($strNum3) {


$s1 = floor($strNum3/100);
$d1 = floor(($strNum3 % 100)/10);
$d2 = $strNum3 % 100;
$v1 = $strNum3 % 10;

$s3 = $d3 = $v3 = "";

switch ($s1) {
Case 1:
	$s3 = "VIENAS ŠIMTAS "; break;
Case 2:
	$s3 = "DU ŠIMTAI "; break;
Case 3:
	$s3 = "TRYS ŠIMTAI "; break;
Case 4:
	$s3 = "KETURI ŠIMTAI "; break;
Case 5:
	$s3 = "PENKI ŠIMTAI "; break;
Case 6:
	$s3 = "ŠEŠI ŠIMTAI "; break;
Case 7:
	$s3 = "SEPTYNI ŠIMTAI "; break;
Case 8:
	$s3 = "AŠTUONI ŠIMTAI "; break;
Case 9:
	$s3 = "DEVYNI ŠIMTAI "; break;
}


switch ($d1) {
Case 1:
	switch ($d2) {
	Case 10:
	$d3 = "DEŠIMT "; break;
	Case 11:
	$d3 = "VIENUOLIKA "; break;
	Case 12:
	$d3 = "DVYLIKA "; break;
	Case 13:
	$d3 = "TRYLIKA "; break;
	Case 14:
	$d3 = "KETURIOLIKA "; break;
	Case 15:
	$d3 = "PENKIOLIKA "; break;
	Case 16:
	$d3 = "ŠEŠIOLIKA "; break;
	Case 17:
	$d3 = "SEPTYNIOLIKA "; break;
	Case 18:
	$d3 = "AŠTUONIOLIKA "; break;
	Case 19:
	$d3 = "DEVYNIOLIKA "; break;
	}
	break;
Case 2:
	$d3 = "DVIDEŠIMT "; break;
Case 3:
	$d3 = "TRISDEŠIMT "; break;
Case 4:
	$d3 = "KETURIASDEŠIMT "; break;
Case 5:
	$d3 = "PENKIASDEŠIMT "; break;
Case 6:
	$d3 = "ŠEŠIASDEŠIMT "; break;
Case 7:
	$d3 = "SEPTYNIASDEŠIMT "; break;
Case 8:
	$d3 = "AŠTUONIASDEŠIMT "; break;
Case 9:
	$d3 = "DEVYNIASDEŠIMT "; break;
}

If ($d1 != 1) {
	switch ($v1) {
	Case 1:
	$v3 = "VIENAS "; break;
	Case 2:
	$v3 = "DU "; break;
	Case 3:
	$v3 = "TRYS "; break;
	Case 4:
	$v3 = "KETURI "; break;
	Case 5:
	$v3 = "PENKI "; break;
	Case 6:
	$v3 = "ŠEŠI "; break;
	Case 7:
	$v3 = "SEPTYNI "; break;
	Case 8:
	$v3 = "AŠTUONI "; break;
	Case 9:
	$v3 = "DEVYNI "; break;
	}
}
return $s3 . $d3 . $v3;

}

function removeLtChars($input){
	$output = str_replace("ą","a",$input);
	$output = str_replace("č","c",$output);
	$output = str_replace("ę","e",$output);
	$output = str_replace("ė","e",$output);
	$output = str_replace("į","i",$output);
	$output = str_replace("š","s",$output);
	$output = str_replace("ų","u",$output);
	$output = str_replace("ū","u",$output);
	$output = str_replace("ž","z",$output);
	$output = str_replace("Ą","A",$output);
	$output = str_replace("Č","C",$output);
	$output = str_replace("Ę","E",$output);
	$output = str_replace("Ė","E",$output);
	$output = str_replace("Į","I",$output);
	$output = str_replace("Š","S",$output);
	$output = str_replace("Ų","U",$output);
	$output = str_replace("Ū","U",$output);
	$output = str_replace("Ž","Z",$output);
	RETURN $output;
}

function subtractDaysFromToday($number_of_days)
{
    $today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

    $subtract = $today - (86400 * $number_of_days);

    //choice a date format here
    return date("Y.m.d", $subtract);
}

function logAction($veiksmas,$kodas){
	global $_SESSION;
	if (isset($_SESSION['user']) && isset($_SESSION['company'])) {
		logActionLong($_SESSION['user'],$_SESSION['company'],$veiksmas,$kodas);	
	}
}

function addDocComment($dok_nr,$comment) {
	global $comdel_query,$comins_query, $rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver;
	$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
	if (!$db_rdata->isConnected()) {	
		return;
	}	

	$comdel_query = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comdel_query);
	$db_rdata->execute($comdel_query);
	$comins_query = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comins_query);
	$comins_query = str_replace("<comment>", addslashes_mssql(ltCharsToEntities(htmlspecialchars($comment))), $comins_query);
	$db_rdata->execute($comins_query);
}

function getDocComment($db_rdata,$dok_nr){
	global $comsel_query;
	if (!$db_rdata->isConnected()) {	
		return;
	}
	$sql = str_replace("<dok_nr>", addslashes_mssql($dok_nr), $comsel_query);
	$info = $db_rdata->returnInfo($sql);
	if(!empty($info)){
		return $info["tekstas"];
	} else {
		return;
	}
}

function ltCharsToEntities($input){
	$input = str_replace("ą","&#261;",$input);
	$input = str_replace("č","&#269;",$input);
	$input = str_replace("ę","&#281;",$input);
	$input = str_replace("ė","&#279;",$input);
	$input = str_replace("į","&#303;",$input);
	$input = str_replace("š","&#353;",$input);
	$input = str_replace("ų","&#371;",$input);
	$input = str_replace("ū","&#363;",$input);
	$input = str_replace("ž","&#382;",$input);
	$input = str_replace("Ą","&#260;",$input);
	$input = str_replace("Č","&#268;",$input);
	$input = str_replace("Ę","&#280;",$input);
	$input = str_replace("Ė","&#278;",$input);
	$input = str_replace("Į","&#302;",$input);
	$input = str_replace("Ų","&#370;",$input);
	$input = str_replace("Ū","&#362;",$input);
	$input = str_replace("Š","&#352;",$input);
	$input = str_replace("Ž","&#381;",$input);
	return $input;
}

function logActionLong($vart_id,$vart_pavad,$veiksmas,$kodas){
	global $action_log,$rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver,$_SERVER;
	
	
	if (isset($action_log) && $action_log == "1") {
	
		$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
		if (!$db_rdata->isConnected()) {	
			return;
		}	
	
		$sql = "INSERT INTO History
			   (vart_id,vart_pavad,veiksmas,vart_ip,kodas)
		 VALUES
		   ('".addslashes_mssql(htmlentities($vart_id))."','" 
			   .addslashes_mssql(substr(@iconv( 'UTF-8','windows-1257', htmlspecialchars($vart_pavad)),0,39))."' ,'" 
			   .addslashes_mssql(substr(@iconv( 'UTF-8','windows-1257', htmlspecialchars($veiksmas)),0,39))."' ,'" 
			   .addslashes_mssql($_SERVER['REMOTE_ADDR'])."',".$kodas.")";
		$db_rdata->execute($sql);	   
	}	   
}

function print_file_contents($file) {
	if (file_exists($file)) {
		$fh = fopen($file, 'r');
		$theData = fread($fh, filesize($file));
		fclose($fh);
		echo $theData;
	} else {
		echo "Nerastas failas: " . $file;
	}
}

function getRobotukasInfo(){

	$color = "red";
	$laikas = "";
	if (file_exists('online.txt')) {
		$fhh = fopen('online.txt', 'r');
		$laikas = substr(fread($fhh, filesize('online.txt')),0,32);
		fclose($fhh);
		$laikas_last = strtotime(substr($laikas,0,21));
		$laikas_now = time();
		if (($laikas_last+(12 * 60 * 60)) > $laikas_now) {
			$color = "green";
		} else if ((($laikas_last+(12 * 60 * 60)) <= $laikas_now) 
					&& (($laikas_last+(24 * 60 * 60)) > $laikas_now)) {
			$color = "yellow";		
		}
	}
	return "Robotukas paskutini karta buvo paleistas: " . $laikas . ' <span style="color:'. $color . ';">&diams;</span>';
}

function getVersionInfo(){

	if (file_exists('.svn/entries')) {
		
		$cont = file_get_contents('.svn/entries'); 
		$pos = strpos ($cont,"dir"); 
		$pos2 = strpos ($cont,"\n",$pos+3); 
		$ver = trim(substr($cont,$pos+3,$pos2-$pos+1));
		if (file_exists('gver.txt')) {	
			$modtime = filemtime('gver.txt');
			$skirtumas = time()-$modtime;
			if ($skirtumas > (60*60*24)) {
				$tikrinti = true;
			} else {
				$tikrinti = false;
			}
		} else {
			$tikrinti = true;
		}

		if ($tikrinti) {
				// set url 
				$cont = file_get_contents("http://code.google.com/feeds/p/vsriv/svnchanges/basic?path=/trunk/"); 
				$pos = strpos ($cont,"?r="); 
				if ($pos) {
					$pos2 = strpos ($cont,"&amp;",$pos+4); 
					if ($pos2) {
						$gver = substr($cont,$pos+3,$pos2-$pos-3);
					} else {
						$gver = "";
					}
				} else {
					$gver = "";
				}
			//irasom i faila
			$myFile = "gver.txt";
			$fh = fopen($myFile, 'w');
			fwrite($fh, $gver);
			fclose($fh);		
		} else {
			$gver = file_get_contents("gver.txt");
		}
	} else {
		$ver = "";
		$gver = "";
	}
	if (is_numeric($ver) && is_numeric($gver) && intval($ver) >= intval($gver)) {	
		return "Idiegta naujausia versija: " . $gver;	
	} else {	
		return "Idiegta versija: <span style='color:red;'>" . $ver . "</span>, <b>Naujausia versija: " . $gver . "</b>";	
	}

}

function isMenuSelected($serv_script,$script) {
	$pos = strpos($serv_script, $script);
	if ($pos === false) {
		return "mitem2";
	} else {
		return "mselected";
	}
}
?>